//
//  YPZQDetailViewController.m
//  ChengHuiTong
//
//  Created by CHT-Technology on 2017/2/20.
//  Copyright © 2017年 张文权. All rights reserved.
//

#import "YPZQDetailViewController.h"
#import "YPZQSureViewController.h"
#import "YPInvestDetailViewController.h"
#import "NSDate+Extension.h"

@interface YPZQDetailViewController (){
    
    NSDictionary *_dataDic;
}

@property (nonatomic,strong)UIView *topView;
@property (nonatomic,strong)UIView *middleView;
@property (nonatomic,strong)UIButton *lastView;
@property (nonatomic,strong)UIButton *buyBtn;
@property (nonatomic) dispatch_source_t timer;

@end

@implementation YPZQDetailViewController

#pragma mark -- lazzy
- (UIView *)topView{
    
    if (!_topView) {
        
        _topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, autoScaleH(140))];
        _topView.backgroundColor = [UIColor whiteColor];
        
        
        
        UILabel *titleLabel = [UILabel creatWithFrame:CGRectMake(leftMargin, 0, SCREEN_WIDTH, autoScaleH(40))
                                                 font:[UIFont systemFontOfSize:15]
                                                 text:_dataDic[@"title"]
                                            textColor:[UIColor blackColor]
                                        textAlignment:0];
        [_topView addSubview:titleLabel];
        
        
        
        UILabel *aprLabel = [UILabel creatWithFrame:CGRectMake(titleLabel.left, titleLabel.bottom, (SCREEN_WIDTH - leftMargin*2)/2.f, autoScaleH(25))
                                               font:[UIFont systemFontOfSize:12]
                                               text:@""
                                          textColor:kColor_AppNavColor
                                      textAlignment:0];
        aprLabel.attributedText = [AppTools getAttributedStringWithRate:_dataDic[@"apr"]
                                                                rateAdd:nil fontSize:25];
        [_topView addSubview:aprLabel];
        UILabel *apr = [UILabel creatWithFrame:CGRectMake(aprLabel.left, aprLabel.bottom, aprLabel.width, aprLabel.height)
                                          font:[UIFont systemFontOfSize:12]
                                          text:@"参考年化收益率"
                                     textColor:kColor_greyAshTitleColor
                                 textAlignment:0];
        [_topView addSubview:apr];
        
        
        
        UILabel *timeLimit = [UILabel creatWithFrame:CGRectMake(aprLabel.right + leftMargin , aprLabel.top, 0, apr.height)
                                                font:apr.font
                                                text:@"剩余期数"
                                           textColor:kColor_greyAshTitleColor
                                       textAlignment:0];
        [_topView addSubview:timeLimit];
        timeLimit.width = [timeLimit.text widthWithFont:timeLimit.font height:timeLimit.height];
        UILabel *timeLimitLabel = [UILabel creatWithFrame:CGRectMake(timeLimit.right + 10, timeLimit.top, aprLabel.width - timeLimit.width - 10, timeLimit.height)
                                                     font:[UIFont systemFontOfSize:15]
                                                     text:[NSString stringWithFormat:@"%@个月",_dataDic[@"remain_periods"]]
                                                textColor:[UIColor blackColor]
                                            textAlignment:0];
        [_topView addSubview:timeLimitLabel];
        
        
        
        UILabel *totalMoney = [UILabel creatWithFrame:CGRectMake(timeLimit.left, apr.top, timeLimit.width, timeLimit.height)
                                                 font:timeLimit.font
                                                 text:@"转让价格"
                                            textColor:kColor_greyAshTitleColor
                                        textAlignment:0];
        [_topView addSubview:totalMoney];
        UILabel *totalMoneyLabel = [UILabel creatWithFrame:CGRectMake(timeLimitLabel.left, totalMoney.top, timeLimitLabel.width, timeLimitLabel.height)
                                                      font:[UIFont systemFontOfSize:15]
                                                      text:_dataDic[@"sale_price"]
                                                 textColor:[UIColor blackColor]
                                             textAlignment:0];
        [_topView addSubview:totalMoneyLabel];
        
        
        UILabel *timeLabel = [UILabel creatWithFrame:CGRectMake(aprLabel.left, totalMoneyLabel.bottom + autoScaleH(20), aprLabel.width-leftMargin, autoScaleH(30))
                                                font:[UIFont systemFontOfSize:12]
                                                text:@""
                                           textColor:[UIColor blackColor]
                                       textAlignment:2];
        timeLabel.attributedText = [AppTools getAttributedStringWithImage:[UIImage imageNamed:@"daojishi"] string:_complete?@" 完成时间":@" 投资剩余时间"];
        [_topView addSubview:timeLabel];
        UILabel *lastTime = [UILabel creatWithFrame:CGRectMake(timeLabel.right, timeLabel.top, SCREEN_WIDTH - timeLabel.right, autoScaleH(30))
                                               font:[UIFont systemFontOfSize:12]
                                               text:@""
                                          textColor:[UIColor blackColor]
                                      textAlignment:0];
        lastTime.tag = 199;
        if (!_complete) {
            [self handleTimerWithLabel:lastTime];
        }else{
            NSString *endTime;
            if ([_dataDic[@"buy_time"] integerValue] == 0) {
                endTime = _dataDic[@"expire_time"];
            }else{
                endTime = _dataDic[@"buy_time"];
            }
            lastTime.text = [NSDate getDateWithInterval:[endTime doubleValue] formart:@"  yyyy-MM-dd HH:mm:ss"];
        }
        
        [_topView addSubview:lastTime];
        
        
        [_topView addLineWithFrame:CGRectMake(apr.right - leftMargin, aprLabel.top + autoScaleH(6), 0.5, apr.bottom - aprLabel.top - autoScaleH(6)*2) color:colorWithRGB(230, 230, 230)];
        [_topView addLineWithFrame:CGRectMake(leftMargin, lastTime.top - (autoScaleH(30)-lastTime.height)/2.f, SCREEN_WIDTH - leftMargin*2, 0.5) color:colorWithRGB(230, 230, 230)];
        [_topView addLine];
    }

    return _topView;
}

- (UIView *)middleView{
    
    if (!_middleView) {
        _middleView = [[UIView alloc]initWithFrame:CGRectMake(0, self.topView.bottom + autoScaleH(8), SCREEN_WIDTH, autoScaleH(170))];
        _middleView.backgroundColor = [UIColor whiteColor];
        NSArray *dataArray = @[@"债权价值   ",@"待收本金   ",@"下期还款   ",@"还款方式   ",@"保障方式   "];
        NSArray *changeArray = @[[NSString stringWithFormat:@"%@元",_dataDic[@"credit_value"]],[NSString stringWithFormat:@"%@元",_dataDic[@"wait_capital"]],_dataDic[@"next_repay_date"],YPGetRepayments(_dataDic[@"style"]),@"风险准备金垫付"];
        for (int i = 0; i < dataArray.count; i ++) {
            UILabel *label = [UILabel creatWithFrame:CGRectMake(leftMargin, autoScaleH(35)*i, SCREEN_WIDTH - leftMargin*2, autoScaleH(30))
                                                font:[UIFont systemFontOfSize:13]
                                                text:@""
                                           textColor:kColor_greyAshTitleColor
                                       textAlignment:0];
            label.attributedText = [self getAttributedStringWithOriginalString:[NSString stringWithFormat:@"%@%@",dataArray[i],changeArray[i]] changeString:changeArray[i]];
            [_middleView addSubview:label];
        }
        [_middleView addLine];
    }
    
    return _middleView;
}

- (UIButton *)lastView{
    
    if (!_lastView) {
        _lastView = [UIButton creatWithFrame:CGRectMake(0, self.middleView.bottom + autoScaleH(8), SCREEN_WIDTH, autoScaleH(40))
                                        font:[UIFont systemFontOfSize:15]
                                        text:@"查看原标详情"
                                   textColor:[UIColor blackColor]
                                       image:[UIImage imageNamed:@"chakanxq"]
                                      action:@selector(goOriginalDetail)
                                      target:self];
        _lastView.backgroundColor = [UIColor whiteColor];
        [_lastView setTitleLeftImageRightWithWidthSpace:leftMargin];
    }
    return _lastView;
}

- (UIButton *)buyBtn{
    
    if (!_buyBtn) {
        _buyBtn = [UIButton creatWithFrame:CGRectMake(0, SCREEN_HEIGHT - autoScaleH(50) - 64, SCREEN_WIDTH, autoScaleH(50))
                                      font:[UIFont systemFontOfSize:18]
                                      text:_complete?@"已售罄":@"立即认购"
                                    action:@selector(buyClick)
                                    target:self];
        _buyBtn.backgroundColor = _complete?[UIColor lightGrayColor]:kColor_AppNavColor;
        _buyBtn.enabled = !_complete;
    }
    return _buyBtn;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navigationItem.title = @"债权转让";
    
    [self setUpdata];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (self.timer) {
         dispatch_source_cancel(self.timer);
    }
   
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (self.view.subviews.count > 0) {
        UILabel *label = [_topView viewWithTag:199];
        if (label && _complete == NO && [_dataDic.allKeys containsObject:@"expire_time"] ) {
            [self handleTimerWithLabel:label];
        }
    }
    
}

- (void)setUpdata{
    
    [YPHttpRequestMethod sendAsyRequestURL:CMD_ZQZRDETAIL withData:@{@"tid":REALSTRING(_tid)} withCompletionBlock:^(NSDictionary *responseDictionary) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([responseDictionary[@"status"] intValue]== 0) {
            
            _dataDic = responseDictionary;
            [self setUpUI];
        }
        
    } withFailedBlock:^(NSError *error) {
        
    }withIndicator:YES  atView:self.view];

}

- (void)setUpUI{

    [self.view addSubview:self.topView];
    [self.view addSubview:self.middleView];
    [self.view addSubview:self.lastView];
    [self.view addSubview:self.buyBtn];
    
}

- (NSAttributedString *)getAttributedStringWithOriginalString:(NSString *)originalString
                                                  changeString:(NSString *)changeString
{
    
    NSMutableAttributedString *mAttString = [[NSMutableAttributedString alloc]initWithString:originalString];
    [mAttString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],
                                NSForegroundColorAttributeName:[UIColor blackColor],
                                } range:[originalString rangeOfString:changeString]];
  
    return mAttString;
}

#pragma mark -- 事件响应
-(void)handleTimerWithLabel:(UILabel *)label;
{
    
    __block NSCalendar *calendar;
    double delayInSeconds = 1.0;
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC, 0.0);
    dispatch_source_set_event_handler(_timer, ^{
        
        if (!calendar) {
            calendar = [NSCalendar currentCalendar];
        }

        NSDate *fireDate = [NSDate dateWithTimeIntervalSince1970:[_dataDic[@"expire_time"] doubleValue]];//目标时间
        NSDate *today = [NSDate date];//当前时间
        
        unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
        NSDateComponents *d = [calendar components:unitFlags fromDate:today toDate:fireDate options:0];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            label.text = [NSString stringWithFormat:@"  %ld天%ld小时%ld分%ld秒", (long)[d day], (long)[d hour], (long)[d minute], (long)[d second]];
        });
    });
    //激活timer
    dispatch_resume(_timer);


}

- (void)goOriginalDetail{
    
    YPInvestDetailViewController * investDetailVC = [[YPInvestDetailViewController alloc]init];
    YPInvestModel *model = [[YPInvestModel alloc]init];
    model.bid = _dataDic[@"borrow_id"];
    model.title = _dataDic[@"title"];
    investDetailVC.investModel = model;
    [self.navigationController pushViewController:investDetailVC animated:YES];
}

- (void)buyClick{
    
    if (TOKEN) {
        [self goSureVC];
    }else{
        WeakSelf
        [self goToLoginVCWithCompleteBlock:^(NSString *token) {
            [weakSelf goSureVC];
        }];
    }
}

- (void)goSureVC{
    
    YPZQSureViewController *sureVC = [[YPZQSureViewController alloc]init];
    sureVC.tid = _tid;
    [self.navigationController pushViewController:sureVC animated:YES];
}

@end
